package com.hsteach.service.equipment;

import com.google.common.collect.Lists;
import com.hsteach.common.config.App;
import com.hsteach.common.config.AppConfig;
import com.hsteach.common.core.domain.model.AuthInfo;
import com.hsteach.common.exception.ServiceException;
import com.hsteach.common.utils.SecurityUtils;
import com.hsteach.dao.domain.equipment.EquipmentRepair;
import com.hsteach.dao.domain.equipment.EquipmentRepairConfig;
import com.hsteach.dao.domain.equipment.EquipmentRepairFiles;
import com.hsteach.dao.domain.equipment.EquipmentRepairResult;
import com.hsteach.dao.mapper.equipment.EquipmentRepairConfigMapper;
import com.hsteach.dao.mapper.equipment.EquipmentRepairFilesMapper;
import com.hsteach.dao.mapper.equipment.EquipmentRepairMapper;
import com.hsteach.dao.mapper.equipment.EquipmentRepairResultMapper;
import com.hsteach.enums.MsgTypeEnum;
import com.hsteach.framework.feign.client.xgk.dto.ret.GetTeacherRet;
import com.hsteach.service.third.MessageService;
import com.hsteach.service.third.XgkService;
import com.hsteach.util.ConstantCode;
import com.hsteach.web.controller.equipment.dto.EquipmentPublicDto;
import com.hsteach.web.controller.equipment.dto.EquipmentRepairResultDto;
import com.hsteach.web.controller.equipment.dto.PersonVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 设备维修服务层
 */
@Slf4j
@Service
public class EquipmentRepairResultService {

    @Autowired
    private EquipmentRepairMapper equipmentRepairMapper;

    @Autowired
    private EquipmentRepairFilesMapper equipmentRepairFilesMapper;

    @Autowired
    private EquipmentRepairResultMapper equipmentRepairResultMapper;

    @Autowired
    private EquipmentRepairConfigMapper equipmentRepairConfigMapper;

    @Autowired
    private MessageService messageService;

    @Autowired
    private XgkService xgkService;

    @Autowired
    private AppConfig appConfig;


    /**
     *维修职工查询设备维修列表
     * @return
     */
    public List<EquipmentRepair> qureyList(EquipmentPublicDto equipmentPublicDto) {
        EquipmentPublicDto dto = new EquipmentPublicDto();
        dto.setStatus(equipmentPublicDto.getStatus());
        dto.setRepairType(equipmentPublicDto.getRepairType());
        dto.setPersonId(SecurityUtils.getAuthInfo().getPersonId());
        dto.setOrgCode(SecurityUtils.getAuthInfo().getOrgCode());
        dto.setBuildingLocation(equipmentPublicDto.getBuildingLocation());
        List<EquipmentRepair> list = equipmentRepairMapper.queryListForMaintainer(dto);
        List<String> types = list.stream().map(EquipmentRepair::getRepairType).collect(Collectors.toList());
        EquipmentPublicDto query = new EquipmentPublicDto();
        query.setDelStatus(1);
//        query.setStatus(1);
        query.setOrgCode(SecurityUtils.getAuthInfo().getOrgCode());
        query.setTypes(types);
        List<EquipmentRepairConfig> configs = equipmentRepairConfigMapper.queryListByType(query);
        Map<String, List<EquipmentRepairConfig>> map = configs.stream().collect(Collectors.groupingBy(EquipmentRepairConfig::getRepairType));
        list.forEach(e -> {
            if (map.containsKey(e.getRepairType())) {
                List<PersonVo> ret = map.get(e.getRepairType()).stream().map(j -> {
                    PersonVo vo = new PersonVo();
                    vo.setPersonId(j.getPersonId());
                    vo.setPersonName(j.getPersonName());
                    return vo;
                }).collect(Collectors.toList());
                e.setPersons(ret);
            }
        });
        return list;
    }

    /**
     * 新增维修信息
     * @param equipmentRepairResultDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Long add(EquipmentRepairResultDto equipmentRepairResultDto) {
        EquipmentRepair queryDetail = equipmentRepairMapper.queryDetail(equipmentRepairResultDto.getRepairId());
        if (queryDetail == null) {
            throw new ServiceException("未查询到报修");
        }
        EquipmentRepairResult repairResult = new EquipmentRepairResult();
        repairResult.setRepairId(equipmentRepairResultDto.getRepairId());
        repairResult.setRepairDesc(equipmentRepairResultDto.getRepairDesc());
        repairResult.setPersonId(SecurityUtils.getAuthInfo().getPersonId());
        repairResult.setPersonName(SecurityUtils.getAuthInfo().getName());
        repairResult.setPersonMobile(SecurityUtils.getAuthInfo().getMobile());
        repairResult.setOrgCode(SecurityUtils.getAuthInfo().getOrgCode());
        int i = equipmentRepairResultMapper.insert(repairResult);
        if (i != ConstantCode.ONE){
            throw new RuntimeException("保存维修信息失败!");
        }
        //修改报修信息状态为“已维修”
        EquipmentRepair equipmentRepair = new EquipmentRepair();
        equipmentRepair.setId(equipmentRepairResultDto.getRepairId());
        equipmentRepair.setStatus(ConstantCode.ONE);
        equipmentRepairMapper.update(equipmentRepair);

        //保存维修附件
        if (!ObjectUtils.isEmpty(equipmentRepairResultDto.getFiles()) && equipmentRepairResultDto.getFiles().size()>0){
            EquipmentRepairFiles equipmentRepairFiles = new EquipmentRepairFiles();
            equipmentRepairResultDto.getFiles().forEach(fileVo -> {
                equipmentRepairFiles.setRepairId(repairResult.getId());
                equipmentRepairFiles.setUrl(fileVo.getFileUrl());
                //类型 1图片 2视频 3文件
                equipmentRepairFiles.setFileType(fileVo.getFileType());
                //附件属于报修（repairInfo）/ 维修（resultInfo）
                equipmentRepairFiles.setBelongTo(ConstantCode.RESULT_INFO);
                equipmentRepairFilesMapper.insert(equipmentRepairFiles);
            });
        }
        String msg = queryDetail.getBuildingLocationName() + (queryDetail.getRoomLocationName() == null? "":queryDetail.getRoomLocationName()) + "的" + queryDetail.getRepairType() + "已完成维修";
        sendMsg(Lists.newArrayList(queryDetail.getPersonId()), msg, queryDetail.getId());
        return repairResult.getId();
    }

    private void sendMsg(List<String> toPersonIds, String msg, Long id) {
        try {
            AuthInfo authInfo = SecurityUtils.getAuthInfo();
            String appId = authInfo.getAppId();
            App app = appConfig.getConfig().get(appId);
            if (app == null) {
                return;
            }
            String params = "&type=repairor&msgId=" + id;
//            String encode = URLEncoder.encode(params, "UTF-8");
            String url = app.getRedirectUrl() + params;
            String content = "<p>" + msg + "<a href=\"" + url + "\">跳转进应用</a></p>";
            List<GetTeacherRet> teachers = xgkService.getTeachers(SecurityUtils.getAuthInfo().getId());
            Map<String, String> teacherMap = teachers.stream().filter(e -> e.getT_userID() != null).collect(Collectors.toMap(GetTeacherRet::getPersonId, GetTeacherRet::getT_userID, (v1, v2) -> v2));
            List<String> tPersonId = Lists.newArrayList();
            for (String personId : toPersonIds) {
                if (teacherMap.containsKey(personId)) {
                    tPersonId.add(teacherMap.get(personId));
//                    messageService.addTodothings(msg, teacherMap.get(personId), SecurityUtils.getAuthInfo().getOrganizeId(), "/test", MsgTypeEnum.REPAIR_NOTIFY);
                }
            }
            if (CollectionUtils.isNotEmpty(tPersonId)) {
                messageService.sendMsg(content, tPersonId, MsgTypeEnum.REPAIR_NOTIFY, msg);
            }
        } catch (Exception e) {
            log.error("EquipmentRepairService sendMsg error", e);
        }
    }
}
